package com.code.zg.rxapplication.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.code.zg.rxapplication.R;
import com.code.zg.rxapplication.bean.AppInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zhanggang on 2017/8/25.
 */

public class ApplicationAdapter extends RecyclerView.Adapter<ApplicationAdapter.ViewHolder> {
    List<AppInfo>appInfoList=new ArrayList<>();
    @Override
    public ApplicationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        return new ViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        AppInfo appInfo = appInfoList.get(position);
        holder.name.setText(appInfo.getmName());
        Observable.just(BitmapFactory.decodeFile(appInfo.getmIcon())).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()
        ).subscribe(new Subscriber<Bitmap>() {
            @Override
            public void onCompleted() {
                Log.i("xx", "onCompleted: ");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Bitmap bitmap) {
                holder.image.setImageBitmap(bitmap);
            }
        });
//        holder.image.setImageBitmap(BitmapFactory.decodeFile(appInfo.getmIcon()));
    }
    public void addApplication(List<AppInfo>applications){
        appInfoList.clear();
        appInfoList.addAll(applications);
        notifyDataSetChanged();
    }
    public void addApplication(AppInfo info,int position){
        if(position<0){
            position=0;
        }
        appInfoList.add(position,info);
        notifyItemInserted(position);
    }

    @Override
    public int getItemCount() {
        return appInfoList.size();
    }
    public static class ViewHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.name)
        TextView name;
        @BindView(R.id.image)
        ImageView image;
        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
//            name= (TextView) itemView.findViewById(R.id.name);
//            image= (ImageView) itemView.findViewById(R.id.image);
        }
    }
}
